//
//  MSInputAttachView.m
//  MSJD
//
//  Created by xiangbo on 2018/12/10.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSInputAttachView.h"
#import "MSCommentSendViewCell.h"
#import "TZImagePickerController.h"
#import "MSAddImgCollectionViewCell.h"

static NSString *cellId = @"MSCommentSendViewCell";
static NSString *addImgCellId = @"MSAddImgCollectionViewCell";

@interface MSInputAttachView () <UICollectionViewDelegate, UICollectionViewDataSource, TZImagePickerControllerDelegate, MSCommentSendViewCellDelegate> {
    NSNumber *_videoId;
}

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, assign) MSCommentPublishType type;
@property (nonatomic, weak) MBProgressHUD *progressHUD;

@end

@implementation MSInputAttachView

- (instancetype)init {
    self = [super init];
    if (self) {
        [self initInterface];
    }
    return self;
}

- (void)initInterface {
    [self addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self);
    }];
    _attachViewHeight = 70;
    [self configureCollectionViewWithType:MSCommentPublishTypeImage];
}

#pragma mark - private

- (long long)fileSizeAtPath:(NSString*)filePath
{
    if (filePath.length == 0) {
        return 0;
    }
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize]/1000/1000;
    }
    return 0;
}

#pragma mark - Action
- (void)chooseImageAction {
    [self pushPickerControllerWithType:MSCommentPublishTypeImage];
}

- (void)chooseVideoAction {
    [self pushPickerControllerWithType:MSCommentPublishTypeVideo];
}

- (void)pushPickerControllerWithType:(MSCommentPublishType)chooseType {
    TZImagePickerController *imagePickerVc = nil;
    if (chooseType == MSCommentPublishTypeImage) {
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
        imagePickerVc.selectedAssets = [_selectedAssets mutableCopy];
        imagePickerVc.allowTakePicture = YES;
        imagePickerVc.allowTakeVideo = NO;
        imagePickerVc.allowPickingGif = YES;
        imagePickerVc.allowPickingMultipleVideo = YES;
    }else {
        imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:3 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
        imagePickerVc.selectedAssets = [_selectedAssets mutableCopy];
        imagePickerVc.allowPickingMultipleVideo = NO;
        imagePickerVc.allowPickingGif = NO;
        imagePickerVc.allowTakePicture = NO;
        imagePickerVc.allowTakeVideo = YES;
        imagePickerVc.videoMaximumDuration = 30;
        imagePickerVc.maxImagesCount = 1;
    }
    imagePickerVc.allowPickingOriginalPhoto = NO;
    imagePickerVc.barItemTextColor = [UIColor colorWithRed:255 green:95 blue:0 alpha:1];
    imagePickerVc.iconThemeColor = [UIColor colorWithRed:255 green:95 blue:0 alpha:1];
    imagePickerVc.oKButtonTitleColorNormal =[UIColor colorWithRed:255 green:95 blue:0 alpha:1];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor colorWithRed:255 green:95 blue:0 alpha:0.5];
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    [[UIViewController currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - TZImagePickerControllerDelegate

- (void)tz_imagePickerControllerDidCancel:(TZImagePickerController *)picker {
    [self focus];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    [self focus];
    _selectedPhotos = [photos copy];
    _selectedAssets = [assets copy];
    [self configureCollectionViewWithType:MSCommentPublishTypeImage];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    [self focus];
    _selectedPhotos = coverImage ? @[coverImage]:nil;
    _selectedAssets = asset ? @[asset]:nil;
    [self configureCollectionViewWithType:MSCommentPublishTypeVideo];
}

- (void)configureCollectionViewWithType:(MSCommentPublishType)type {
    self.type = type;
    self.collectionView.hidden = NO;
    [self updateContentHeight];
    [self.collectionView reloadData];
    if (self.selectedPhotos.count > 3) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [_collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:[self collectionView:_collectionView numberOfItemsInSection:0]-1 inSection:0] atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
        });
    }
}

- (void)updateContentHeight {
    if (self.delegate && [self.delegate respondsToSelector:@selector(inputAttachView:changeHeight:)]) {
        [self.delegate inputAttachView:self changeHeight:_attachViewHeight];
    }
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0);
    }];
    [self layoutIfNeeded];
}

- (void)focus {
//    if (self.delegate && [self.delegate respondsToSelector:@selector(didFinishPickingPhotosWithAttachView:)]) {
//        [self.delegate didFinishPickingPhotosWithAttachView:self];
//    }
}

#pragma mark - MSCommentSendViewCellDelegate
- (void)commentSendViewCell:(MSCommentSendViewCell *)MSCommentSendViewCell didDeleteIndex:(NSInteger)index {
    [self deleteArrayAtIndex:index];
    [self configureCollectionViewWithType:self.type];
}

- (void)commentSendViewCellDidClickedMoreAction:(MSCommentSendViewCell *)commentSendViewCell {
}

- (void)deleteArrayAtIndex:(NSInteger)index {
    _selectedAssets = [self deleteArray:_selectedAssets atIndex:index];
    _selectedPhotos = [self deleteArray:_selectedPhotos atIndex:index];
    
}

- (NSArray *)deleteArray:(NSArray *)array atIndex:(NSInteger)index {
    NSMutableArray *mutArray = [NSMutableArray arrayWithArray:array];
    if (mutArray.count > index) {
        [mutArray removeObjectAtIndex:index];
    }
    return [mutArray copy];
}

- (UIImage *)selectedPhotoIndex:(NSInteger)index {
    if (index < _selectedPhotos.count) {
        return _selectedPhotos[index];
    }
    return nil;
}

#pragma mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.selectedPhotos.count < 3) {
        return self.selectedPhotos.count + 1;
    }
    return self.selectedPhotos.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectedPhotos.count > indexPath.row) {
        MSCommentSendViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];
        cell.imageView.image = [self selectedPhotoIndex:indexPath.row];
        cell.deleteBtn.tag = indexPath.row;
        cell.delegate = self;
        return cell;
    } else {
        MSAddImgCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:addImgCellId forIndexPath:indexPath];
        return cell;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (self.selectedPhotos.count <= indexPath.row) {
        [self chooseImageAction];
    }
}


#pragma mark - Property
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumInteritemSpacing = 12;
        layout.minimumLineSpacing = 12;
        layout.itemSize = CGSizeMake(70, 70);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.showsHorizontalScrollIndicator = NO;
        if ([_collectionView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
            if (@available(iOS 10.0, *)) {
                _collectionView.prefetchingEnabled = NO;
            } else {
                // Fallback on earlier versions
            }
        }
        _collectionView.hidden = YES;
        [_collectionView registerClass:[MSCommentSendViewCell class] forCellWithReuseIdentifier:cellId];
        [_collectionView registerClass:MSAddImgCollectionViewCell.class forCellWithReuseIdentifier:addImgCellId];
    }
    return _collectionView;
}

- (void)setProgressHUD:(MBProgressHUD *)progressHUD {
    if (_progressHUD && _progressHUD != progressHUD) {
        [_progressHUD hideAnimated:NO];
    }
    _progressHUD = progressHUD;
}

- (void)dealloc {
    _collectionView.delegate = nil;
    _collectionView.dataSource = nil;
    _collectionView = nil;
}

@end
